package framework.view;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import java.util.*;

import framework.model.*;
import framework.controller.*;
import framework.gui.LobbyGUI;

/**
 * @class BoardGameView
 * @author Michel Jansma
 * @version 0.1
 */
public class BoardGameView extends InteractiveView {

	/**********************
	 *** GLOBAL METHODS ***
	 *********************/
	
	/**
	 * Initialize BoardGameView
	 * @method BoardGameView (Constructor)
	 * @param <GameModel> model
	 * @param <GameController> controller
	 */
	public BoardGameView(GameModel model, GameController controller) {
		super(model,controller);
		this.getModel().addListener(this);
		this.initialize();
	};
	
	/**
	 * @method initialize
	 */
	public void initialize() {
		try {
			this.getController().setGameSettings();	
		} catch(Exception e) {
			//Show settings dialog
			this.getController().getSettingsDialog((JFrame)SwingUtilities.getWindowAncestor(this));
			this.initialize();
		} finally {
			//Set GameSettings data
			this.getController().setResources();
			this.getController().setBoard();
		};
	};
	
	private void updateBoard() {
		//Remove all items
		this.removeAll();
		//Set layout
		this.setLayout(new GridLayout(this.getModel().getBoardHeight(),this.getModel().getBoardWidth()));
		//Add items to GameView
		int[][] board = this.getModel().getBoard();
		//Loop through board records
		for(int i = 0; i < board.length; i++) {
			//Loop through board columns 
			for(int j = 0; j < board[i].length; j++) {
				//Get player by player index
				HashMap<String,String> player = this.getModel().getPlayer(board[i][j]);
				if(player != null) {
					super.add(new JButton(new ImageIcon(player.get("resource"))));	
				} else {
					JButton button = new JButton(String.valueOf(this.getModel().board2DToId(j, i)));		
					button.setActionCommand("player_move");
					button.addActionListener(this);
					super.add(button);	
				};
			};
		};
		//Repaint view
		super.validate();
		super.repaint();
	};
	
	@Override 
	public void actionPerformed(ActionEvent e) {
		switch(e.getActionCommand()) {
			case "board_updated" :
				this.updateBoard();
			break;
			case "player_move" :
				int digit = Integer.parseInt(((JButton)e.getSource()).getText());
				this.getController().handleMoveRequest(digit);
			break;
			case "game_message_updated" :
				JOptionPane.showMessageDialog(this, this.getModel().getGameMessage());
				SwingUtilities.getWindowAncestor(this).dispose();
				this.getController().handleShutdownRequest();
			break;
		}; 
	};
	
	/**********************
	 *** GETTER METHODS ***
	 *********************/
	
	@Override
	public GameModel getModel() {
		return (GameModel) super.getModel();
	};
	
	@Override
	public GameController getController() {
		return (GameController) super.getController();
	};
	
}
